package com.hy.study.practice.linkedlist;

/**
 * 单链表 练习
 */
public class SingleLinkedListDemo1 {
    public static void main(String[] args) {
        Node1 zhangsan = new Node1(1, "zhangsan");
        Node1 lisi = new Node1(2, "lisi");
        Node1 wangwu = new Node1(3, "wangwu");
        Node1 zhaoliu = new Node1(4, "zhaoliu");

        NodeList1 nodeList1 = new NodeList1();
//        nodeList1.add(zhangsan);
//        nodeList1.add(lisi);
//        nodeList1.add(wangwu);
//        nodeList1.add(zhaoliu);

        nodeList1.addOrderBy(wangwu);
        nodeList1.addOrderBy(lisi);
        nodeList1.addOrderBy(zhaoliu);
        nodeList1.addOrderBy(zhangsan);
        nodeList1.addOrderBy(zhangsan);
        nodeList1.list();
    }
}

class NodeList1 {
    //头节点
    private Node1 head = new Node1();

    public void list() {
        Node1 temp = head.getNextNode();
        while (true) {
            if (temp == null) {
                break;
            }
            System.out.println(temp);
            temp = temp.getNextNode();
        }
    }

    public void addOrderBy(Node1 node){
        Node1 temp=head;
        boolean flag=false;
        while (true){
            if(temp.getNextNode()==null){
                //链表为空
                break;
            }
            if(temp.getNextNode().getNo()>node.getNo()){
                //找到插入的位置
                break;
            }else if(temp.getNextNode().getNo()==node.getNo()){
                //里面有相等的元素
                flag=true;
                break;
            }
            temp=temp.getNextNode();
        }
        if(flag){
            System.out.println("链表中存在相同的元素 无法添加元素");
        }else {
            node.setNextNode(temp.getNextNode());
            temp.setNextNode(node);
        }
    }


    /**
     * 添加元素
     *
     * @param node
     */
    public void add(Node1 node) {
        //查找最后一个元素 将最后一个元素的next 设置为当前节点
        Node1 temp = head;
        while (true) {
            if (temp.getNextNode() == null) {
                //找到了
                break;
            }
            temp = temp.getNextNode();
        }
        temp.setNextNode(node);
    }

}

class Node1 {
    public Node1() {
    }

    public Node1(int no, String name) {
        this.no = no;
        this.name = name;
    }

    private int no;
    private String name;
    private Node1 nextNode;

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Node1 getNextNode() {
        return nextNode;
    }

    @Override
    public String toString() {
        return "Node1{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }

    public void setNextNode(Node1 nextNode) {
        this.nextNode = nextNode;
    }
}